package com.gmall.common.util;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.util.UUID;

/**
 * Project:gmall-common
 * File: com.gmall.cloud.common.core.util
 *
 * @author : hl.wu
 * @date : 2019-06-06
 * <p>
 * 密码加密/匹配
 */
public class PasswordUtils {

    private final static HashFunction md5 = Hashing.md5();
    private final static Joiner joiner = Joiner.on('@').skipNulls();
    private final static Splitter splitter = Splitter.on('@').trimResults();
    private final static HashFunction sha512 = Hashing.sha512();


    /**
     * 对密码进行加密
     *
     * @param password
     * @return 返回加密后的密码
     */
    public static String encrypt(String password) {
        String salt = md5.newHasher().putUnencodedChars(UUID.randomUUID().toString())
                .putLong(System.currentTimeMillis()).hash().toString().substring(0, 4);
        String realPassword = sha512.hashUnencodedChars(password + salt).toString().substring(0, 20);
        return joiner.join(salt, realPassword);
    }

    /**
     * 验证密码是否匹配
     *
     * @param password          提交的明文密码
     * @param encryptedPassword 数据库存储的加密密码
     * @return
     */
    public static boolean match(String password, String encryptedPassword) {
        Iterable<String> parts = splitter.split(encryptedPassword);
        String salt = Iterables.get(parts, 0);
        String realPassword = Iterables.get(parts, 1);
        return com.google.common.base.Objects.equal(sha512.hashUnencodedChars(password + salt).toString().substring(0, 20), realPassword);
    }

}
